package citic.c.util.compare;

import java.math.BigDecimal;
import java.text.Collator;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringCompare implements Comparator<String> {

    private static final Pattern PATTERN = Pattern.compile("\\D*(\\d+)\\D*");

    @Override
    public int compare(String o1, String o2) {
        if (o1 == null || o2 == null) {
            return 0;
        }

        BigDecimal bo1 = convertNum(o1);
        BigDecimal bo2 = convertNum(o2);
        if (bo1 == null || bo2 == null) {
            // 中间 1-多个数字
            Matcher matcher1 = PATTERN.matcher(o1);
            Matcher matcher2 = PATTERN.matcher(o2);
            int indexStep1 = 0;
            int indexStep2 = 0;
            while (matcher1.find()) {
                String s1 = matcher1.group(1);
                String s2;
                if (matcher2.find()) {
                    s2 = matcher2.group(1);
                } else {
                    break;
                }
                int index1 = o1.indexOf(s1, indexStep1);
                int index2 = o2.indexOf(s2, indexStep2);
                //
                indexStep1 = index1 + s1.length();
                indexStep2 = index2 + s2.length();

                String pre1 = o1.substring(0, index1).replace(" ", "");
                String pre2 = o2.substring(0, index2).replace(" ", "");
                if (pre1.equals(pre2)) {

                    long num1 = Long.parseLong(s1);
                    long num2 = Long.parseLong(s2);
                    if (num1 != num2) {
                        return (int) (num1 - num2);
                    }
                } else {
                    return Collator.getInstance(Locale.CHINA).compare(o1, o2);
                }
            }
            return Collator.getInstance(Locale.CHINA).compare(o1, o2);
        } else {
            return bo1.compareTo(bo2);
        }
    }

    private static BigDecimal convertNum(String s) {
        try {
            return new BigDecimal(s);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public boolean equals(Object obj) {
        return false;
    }

    public static void main(String[] args) {
        List<String> l = new ArrayList<>();
        l.add("1");
        l.add("12");
        l.add("2");
        Collections.sort(l, new StringCompare());
        for (String s : l) {
            System.out.println(s);
        }
    }
}
